import os
import sys
import json
import importlib
import inspect
import argparse
from troubleshooter.migrator.api_checker.compare.compare import Comparator
from troubleshooter.migrator.api_checker.ut_factory import UTFactory


def _run_ut_parser(parser):
    parser.add_argument(
        "-i", "--input", dest="input_file", required=True, type=str,
        help="<Required> Input josn file containing the API information"
    )
    parser.add_argument(
        "-o", "--output", dest="output_path", required=False, type=str,
        help="<Optional> Output path to store the comparison result"
    )
    parser.add_argument(
        "-cpu", dest="cpu_mode", action="store_true", help="<Optional> Compare APIs on CPU mode"
    )


def get_ops_ut(module):
    for name, obj in inspect.getmembers(module):
        if inspect.isclass(obj) and name.startswith("UT"):
            return obj


def _run_ut():
    parser = argparse.ArgumentParser()
    _run_ut_parser(parser)
    args = parser.parse_args(sys.argv[1:])
    json_file = os.path.realpath(args.input_file)
    out_path = os.path.realpath(args.output_path) if args.output_path else "./"
    cpu_mode = args.cpu_mode
    comparator = Comparator(out_path, False)

    with open(json_file, "r") as f:
        api_info = json.load(f)

    for api in api_info:
        for key, value in api.items():
            name, _ = key.split("_")
            if cpu_mode:
                ut_factory = UTFactory(
                    key,
                    value.get("args"),
                    value.get("kwargs"),
                    real_data = value.get("real_data"),
                    stack = value.get("stack"),
                    save_path = value.get("save_path"),
                    comparator=comparator,
                )
                ut_factory.compare()
            else:
                print("ONLY SUPPORT CPU MODE NOW!")


if __name__ == "__main__":
    _run_ut()
